package com.heima.common.aop;

import com.heima.utils.thread.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Enumeration;

@Component
@Aspect
@Slf4j
public class MyAdvice {

    @Pointcut("execution(* com.heima.*.service.*.*(..))")
    public void point() {
    }

//    @Around("point()")
    //有返回值的方法
    public Object runTime(ProceedingJoinPoint pjp) throws Throwable {

        //获取request对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();


        //获取参数数据
        Object[] args = pjp.getArgs();
        //获取调用的方法名方法名
        String target = pjp.getTarget().toString();
        String mode = target.split("\\.")[2];
        String method = target.substring(target.lastIndexOf(".") + 1);
        method=method.split("@")[0];
        String name = pjp.getSignature().getName();

        String userId = null;
        String username = null;
        if (!method.contains("login")) {
            userId = request.getHeader("userId");
            //username = WmThreadLocalUtil.getUser().getName();
        }

        long beginTime = System.currentTimeMillis();   //开始时间
        //输出方法的返回值数据
        Object proceed = pjp.proceed();

        long endTime = System.currentTimeMillis();   //结束时间
        if (userId != null) {
            log.warn("id为" + userId + "的用户访问了: " + mode + "模块--" + method + "类--" + name+ "方法--"  + "执行时间为: " + (endTime - beginTime) + "毫秒");
        }else {
            log.warn("用户登入了" + mode + "模块的类" + method + "的方法" + name + "的执行时间为: " + (endTime - beginTime) + "毫秒");
        }

        //返回原始数据
        return proceed;
    }
}
